﻿using HslCommunication;
using HslCommunication.ModBus;
using HslCommunication.MQTT;
using HuanReZhanDataReceiver;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace FlowerPot
{
    public partial class Form1 : Form
    {
        // 创建一个和客户端通信的套接字
        static Socket socketwatch = null;
        //定义一个集合，存储客户端信息
        static Dictionary<string, Socket> clientConnectionItems = new Dictionary<string, Socket> { };

        private Thread threadwatch = null;

        private static Form1 instance = null;

        private static SqlHelper sqlHelper = new SqlHelper();

        private static List<String> commandToSend = new List<string>();

        private DateTime lastCheckMoveHistoryData = DateTime.MinValue;

        private static DateTime lastSendReadStatus = DateTime.MinValue;

        private MqttClient client;

        private Thread serverThread = null;

        private bool canSend = false;

        private MqttClientService clientService;

        private static RestClient restClient;

        public static Form1 getInstance()
        {
            if (instance == null)
            {
                instance = new Form1();
            }

            return instance;
        }


        public Form1()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();

            txtIP.Text = ConfigurationManager.AppSettings["ServerIP"];
            txtPort.Text = ConfigurationManager.AppSettings["ServerPort"];

            if (Boolean.Parse(ConfigurationManager.AppSettings["AutoStart"]) == true)
            {
                tmrForStart.Enabled = true;
                tmrForStart.Start();
            }

            tmrCheckMoveHistory.Enabled = false;
            tmrCheckMoveHistory.Start();

            this.Text = ConfigurationManager.AppSettings["ProjectName"] + "：" + ConfigurationManager.AppSettings["version"];

            restClient = new RestClient("http://61.171.55.248:8081");

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (btStart.Text.Equals("启动"))
            {
                showLogs(DateTime.Now.Subtract(new TimeSpan(0, int.Parse(Form1.getInstance().txtMiniute.Text), 0)).ToString("yyyy-MM-dd HH:mm:ss") + "-" + "服务器端启动。\r\n");

                try
                {
                    //定义一个套接字用于监听客户端发来的消息，包含三个参数（IP4寻址协议，流式连接，Tcp协议）  
                    socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    //服务端发送信息需要一个IP地址和端口号  
                    IPAddress address = IPAddress.Parse(txtIP.Text);
                    //将IP地址和端口号绑定到网络节点point上  
                    IPEndPoint point = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));
                    //此端口专门用来监听的  

                    //监听绑定的网络节点  
                    socketwatch.Bind(point);

                    //将套接字的监听队列长度限制为20  
                    socketwatch.Listen(20);

                    //负责监听客户端的线程:创建一个监听线程  
                    threadwatch = new Thread(watchconnecting);

                    //将窗体线程设置为与后台同步，随着主线程结束而结束  
                    threadwatch.IsBackground = true;

                    //启动线程     
                    threadwatch.Start();
                }
                catch (Exception ex)
                {
                    showLogs(ex.Message);
                    showError(ex);
                }

                btStart.Text = "停止";
            }
            else if (btStart.Text.Equals("停止"))
            {

                showLogs(DateTime.Now.Subtract(new TimeSpan(0, int.Parse(Form1.getInstance().txtMiniute.Text), 0)).ToString("yyyy-MM-dd HH:mm:ss") + "-" + "服务器端停止。\r\n");

                if (threadwatch != null)
                {
                    threadwatch.Interrupt();
                    threadwatch = null;
                }

                btStart.Text = "启动";
            }
        }


        //监听客户端发来的请求  
        static void watchconnecting()
        {
            try
            {
                Socket connection = null;

                //持续不断监听客户端发来的请求     
                while (true)
                {
                    try
                    {
                        connection = socketwatch.Accept();

                        showLogs("开始循环发送");
                        Form1.getInstance().canSend = true;
                    }
                    catch (Exception ex)
                    {
                        //提示套接字监听异常     
                        //Console.WriteLine(ex.Message);
                        showLogs(ex.Message);
                        showError(ex);
                        break;
                    }

                    //获取客户端的IP和端口号  
                    IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
                    int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;

                    //让客户显示"连接成功的"的信息  
                    //string sendmsg = "连接服务端成功！\r\n" + "本地IP:" + clientIP + "，本地端口" + clientPort.ToString();
                    //byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
                    //connection.Send(arrSendMsg);



                    //客户端网络结点号  
                    string remoteEndPoint = connection.RemoteEndPoint.ToString();
                    //显示与客户端连接情况
                    //Console.WriteLine("成功与" + remoteEndPoint + "客户端建立连接！\t\n");
                    showLogs(DateTime.Now.Subtract(new TimeSpan(0, int.Parse(Form1.getInstance().txtMiniute.Text), 0)).ToString("yyyy-MM-dd HH:mm:ss") + "-" + "接收到客户端" + clientIP + "(" + clientPort + ")" + "的连接...\r\n");

                    //添加客户端信息  
                    clientConnectionItems.Add(remoteEndPoint, connection);

                    //IPEndPoint netpoint = new IPEndPoint(clientIP,clientPort); 
                    IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;

                    //创建一个通信线程      
                    ParameterizedThreadStart pts = new ParameterizedThreadStart(recv);
                    Thread thread = new Thread(pts);
                    //设置为后台线程，随着主线程退出而退出 
                    thread.IsBackground = true;
                    //启动线程     
                    thread.Start(connection);
                }

                showLogs("与客户端的连接已断开！");
            }
            catch (Exception ex)
            {
                showLogs(ex.Message);
                showError(ex);
            }
        }

        /// <summary>
        /// 接收客户端发来的信息，客户端套接字对象
        /// </summary>
        /// <param name="socketclientpara"></param>    
        static void recv(object socketclientpara)
        {
            try
            {
                Socket socketServer = socketclientpara as Socket;
                socketServer.SendBufferSize = 0;

                while (true)
                {

                    //判断是否有要发送的命令
                    if (commandToSend.Count > 0)
                    {
                        String commandLine = null;
                        lock (socketclientpara)
                        {
                            commandLine = commandToSend[0];
                            commandToSend.RemoveAt(0);
                        }

                        byte[] datas = new byte[commandLine.Length / 2];
                        for (int i = 0; i < commandLine.Length / 2; i++)
                        {
                            datas[i] = Convert.ToByte(commandLine.Substring(i * 2, 2), 16);
                        }
                        socketServer.Send(datas);
                        showLogs("发送命令:" + commandLine);
                    }
                    //将接收到的信息存入到内存缓冲区，并返回其字节数组的长度
                    try
                    {
                        if (socketServer.Available > 0)
                        {
                            operateReceiveData(socketServer);
                        }
                    }
                    catch (Exception ex)
                    {
                        clientConnectionItems.Remove(socketServer.RemoteEndPoint.ToString());

                        showLogs("Client Count:" + clientConnectionItems.Count);

                        //提示套接字监听异常  
                        showLogs("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n" + ex.Message + "\r\n" + ex.StackTrace + "\r\n");

                        //关闭之前accept出来的和客户端进行通信的套接字 
                        socketServer.Close();
                        break;
                    }

                    System.Threading.Thread.Sleep(int.Parse(ConfigurationManager.AppSettings["SleepTimeInSec"]) * 1000);
                }

                showLogs("跳出循环2");
            }
            catch (Exception ex)
            {
                showLogs(ex.Message);
                showError(ex);
            }
        }


        public static void showLogs(String logInfo)
        {
            if (Form1.getInstance().chkLogSortDesc.Checked)
            {
                Form1.getInstance().txtLog.Text = DateTime.Now.Subtract(new TimeSpan(0, int.Parse(Form1.getInstance().txtMiniute.Text), 0)).ToString("yyyy-MM-dd HH:mm:ss") + "-" + logInfo + "\r\n" + Form1.getInstance().txtLog.Text;
            }
            else
            {
                Form1.getInstance().txtLog.Text += DateTime.Now.Subtract(new TimeSpan(0, int.Parse(Form1.getInstance().txtMiniute.Text), 0)).ToString("yyyy-MM-dd HH:mm:ss") + "-" + logInfo + "\r\n";
            }

            LogHelper.WriteLog(DateTime.Now.Subtract(new TimeSpan(0, int.Parse(Form1.getInstance().txtMiniute.Text), 0)).ToString("yyyy-MM-dd HH:mm:ss") + "-" + logInfo);

            if (Form1.getInstance().txtLog.Lines.Length > int.Parse(ConfigurationManager.AppSettings["AutoClearLines"]))
            {
                Form1.getInstance().txtLog.Text = "";
                Form1.getInstance().logCounts.Text = "共有日志：0行";
            }
            else
            {
                Form1.getInstance().logCounts.Text = "共有日志：" + Form1.getInstance().txtLog.Lines.Length + "行";
            }
        }

        static void operateReceiveData(Socket socketServer)
        {
            //创建一个内存缓冲区，其大小为1024*1024字节  即1M     
            byte[] arrServerRecMsg = new byte[1024 * 1024];

            int length = socketServer.Receive(arrServerRecMsg);

            //将机器接受到的字节数组转换为人可以读懂的字符串     
            string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);

            if (strSRecMsg.Contains("station") || strSRecMsg.Contains("equi"))
            {
                operateString(socketServer.RemoteEndPoint.ToString(), strSRecMsg, length);
            }
            else
            {
                showLogs("收到客户端数据长度：" + length + "个字节");
                byte[] datas = new byte[length];
                StringBuilder sb = new StringBuilder();

                for (int i = 0; i < length; i++)
                {
                    sb.Append(arrServerRecMsg[i].ToString("X2")).Append(" ");
                }

                operateString(socketServer.RemoteEndPoint.ToString(), sb.ToString().Trim(), length);
            }

            //String[] parts = strSRecMsg.Split(new String[] { "}" }, StringSplitOptions.RemoveEmptyEntries);

            //for (int i = 0; i < parts.Length; i++)
            //{
            //    if(parts[i].Trim().Length > 0)
            //        operateString(socketServer, parts[i] + "}");
            //}

        }

        static void operateString(String remoteEndPoint, String strSRecMsg, int length)
        {
            //这是测试的新代码 

            showLogs("客户端:" + (remoteEndPoint == null?"": remoteEndPoint) + ",time:" + GetCurrentTime() + "\r\n" + strSRecMsg + "\r\n\n");
            if (strSRecMsg.IndexOf("station") >= 0)
            {
                try
                {
                    Dictionary<string, string> resultJSON = JsonConvert.DeserializeObject<Dictionary<string, string>>(strSRecMsg);
                    String station = resultJSON["station"];
                    String data_id = resultJSON["id"];
                    String link = resultJSON["link"];
                    String data_time = resultJSON["time"];
                    String CH1 = resultJSON.ContainsKey("CH1") ? resultJSON["CH1"] : null;
                    String CH2 = resultJSON.ContainsKey("CH2") ? resultJSON["CH2"] : null;
                    String CH3 = resultJSON.ContainsKey("CH3") ? resultJSON["CH3"] : null;
                    String CH4 = resultJSON.ContainsKey("CH4") ? resultJSON["CH4"] : null;
                    String CH5 = resultJSON.ContainsKey("CH5") ? resultJSON["CH5"] : null;

                    showLogs("收到数据  station=" + station + ",id=" + data_id + ",link=" + link + ",time=" + data_time + ",CH1=" + CH1 +
                        ", CH2=" + CH1 + ",CH2=" + CH2 + ",CH3=" + CH3 + ",CH4=" + CH4 + ",CH5=" + CH5);

                    ValueData valueData0 = new ValueData();
                    valueData0.CH1 = int.Parse(CH1);
                    valueData0.CH2 = int.Parse(CH2);
                    valueData0.CH3 = int.Parse(CH3);
                    valueData0.CH4 = int.Parse(CH4);
                    valueData0.CH5 = int.Parse(CH5);
                    String time0 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    string json0 = JsonConvert.SerializeObject(valueData0);
                    String sql0 = "INSERT INTO receive_history_new(station_id,data_id,value,created_time) values('" + station + "'," + data_id + ",'" + json0 + "','" + time0 + "')";

                    SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql0, null);

                    //更新最新的数据
                    String sql1 = @"SELECT count(*) FROM real_datas where station_id='" + station + "' and data_id=" + data_id;
                    int count = int.Parse(SqlHelper.ExecuteScalar(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1).ToString());
                    if (count == 0)
                    {
                        String sql2 = "select * from agriculture_info where station_id = '" + station + "' and id= " + data_id + " and type='alarm_device'";

                        String deviceName = null;
                        String belongto = null;

                        DataSet ds = SqlHelper.GetDataSet(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql2, null);
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            deviceName = ds.Tables[0].Rows[0]["name"].ToString();
                            belongto = ds.Tables[0].Rows[0]["belongto"].ToString();
                        }

                        ValueData valueData = new ValueData();
                        valueData.name = deviceName;
                        valueData.belongto = belongto;
                        valueData.CH1 = int.Parse(CH1);
                        valueData.CH2 = int.Parse(CH2);
                        valueData.CH3 = int.Parse(CH3);
                        valueData.CH4 = int.Parse(CH4);
                        valueData.CH5 = int.Parse(CH5);

                        String time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                        string json = JsonConvert.SerializeObject(valueData);
                        sql1 = "INSERT INTO real_datas(station_id,data_id,value,created_time) values('" + station + "'," + data_id + ",'" + json + "','" + time + "')";
                        SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                    }
                    else
                    {
                        sql1 = "SELECT id,station_id,data_id,value from real_datas where station_id='" + station + "' and data_id=" + data_id;
                        DataSet ds = SqlHelper.GetDataSet(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);


                        Int64 old_id = (Int64)ds.Tables[0].Rows[0][0];
                        String old_station_id = (String)ds.Tables[0].Rows[0][1];
                        Int64 old_data_id = (Int64)ds.Tables[0].Rows[0][2];
                        String old_value = (String)ds.Tables[0].Rows[0][3];

                        String sql2 = "select * from agriculture_info where station_id = '" + station + "' and id= " + data_id + " and type='alarm_device'";

                        String deviceName = null;
                        String belongto = null;

                        ds = SqlHelper.GetDataSet(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql2, null);
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            deviceName = ds.Tables[0].Rows[0]["name"].ToString();
                            belongto = ds.Tables[0].Rows[0]["belongto"].ToString();
                        }
                        else
                        {
                            ValueData oldValue = (ValueData)JsonConvert.DeserializeObject(old_value, typeof(ValueData));
                            deviceName = oldValue.name;
                            belongto = oldValue.belongto;
                        }


                        ValueData valueData = new ValueData();
                        valueData.name = deviceName;
                        valueData.belongto = belongto;
                        valueData.CH1 = int.Parse(CH1);
                        valueData.CH2 = int.Parse(CH2);
                        valueData.CH3 = int.Parse(CH3);
                        valueData.CH4 = int.Parse(CH4);
                        valueData.CH5 = int.Parse(CH5);

                        String time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        string json = JsonConvert.SerializeObject(valueData);
                        sql1 = "UPDATE real_datas set value = '" + json + "',created_time = '" + time + "' where id= " + old_id;
                        SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                    }
                }
                catch (Exception ex)
                {
                    showLogs(ex.Message);
                }
            }
            else if (isModbusData(strSRecMsg)) //读取ModBus的返回值
            {
                if (length == 205)
                {
                    //解析数据
                    ModbusData modbusData = new ModbusData();


                    modbusData.ParseData(strSRecMsg);


                    //更新最新的数据
                    String sql1 = @"SELECT count(*) FROM real_datas where station_id='" + modbusData.Address + "' and data_id=" + modbusData.FunctionNo;
                    int count = int.Parse(SqlHelper.ExecuteScalar(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1).ToString());
                    if (count == 0)
                    {
                        String sql2 = "select * from agriculture_info where station_id = '" + modbusData.Address + "' and type='heat_exchange'";

                        String deviceName = null;
                        String belongto = null;

                        DataSet ds = SqlHelper.GetDataSet(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql2, null);
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            deviceName = ds.Tables[0].Rows[0]["name"].ToString();
                            belongto = ds.Tables[0].Rows[0]["belongto"].ToString();
                        }

                        String time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                        modbusData.name = deviceName;
                        modbusData.belongto = belongto;

                        string json = JsonConvert.SerializeObject(modbusData);
                        sql1 = "INSERT INTO real_datas(station_id,data_id,value,created_time) values('" + modbusData.Address + "'," + modbusData.FunctionNo + ",'" + json + "','" + time + "')";
                        SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                    }
                    else
                    {
                        sql1 = "SELECT id,station_id,data_id,value from real_datas where station_id='" + modbusData.Address + "' and data_id=" + modbusData.FunctionNo;
                        DataSet ds = SqlHelper.GetDataSet(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);


                        Int64 old_id = (Int64)ds.Tables[0].Rows[0][0];
                        String old_station_id = (String)ds.Tables[0].Rows[0][1];
                        Int64 old_data_id = (Int64)ds.Tables[0].Rows[0][2];
                        String old_value = (String)ds.Tables[0].Rows[0][3];


                        String time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");


                        String sql2 = "select * from agriculture_info where station_id = '" + modbusData.Address + "' and type='heat_exchange'";

                        String deviceName = null;
                        String belongto = null;

                        ds = SqlHelper.GetDataSet(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql2, null);
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            deviceName = ds.Tables[0].Rows[0]["name"].ToString();
                            belongto = ds.Tables[0].Rows[0]["belongto"].ToString();
                        }
                        else
                        {
                            ValueData oldValue = (ValueData)JsonConvert.DeserializeObject(old_value, typeof(ValueData));
                            deviceName = oldValue.name;
                            belongto = oldValue.belongto;
                        }

                        modbusData.name = deviceName;
                        modbusData.belongto = belongto;
                        string json = JsonConvert.SerializeObject(modbusData);

                        sql1 = "UPDATE real_datas set value = '" + json + "',created_time = '" + time + "' where id= " + old_id;
                        SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                    }
                }
                else
                {
                }
            }
            else if (strSRecMsg.IndexOf("equi") >= 0 && strSRecMsg.IndexOf("sensor") >= 0)
            {
                try
                {
                    ValueData2 resultJSON = JsonConvert.DeserializeObject<ValueData2>(strSRecMsg, new DataConverter());

                    showLogs("收到数据  equi=" + resultJSON.equi + ",modify-status=" + resultJSON.modifyStatus + ",upload-interval=" + resultJSON.uploadInterval + ",sensor=" + resultJSON.sensor.ToString());

                    String time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    String sql1 = "INSERT INTO receive_history_new(station_id,data_id,value,created_time) values('" + resultJSON.equi + "'," + 1 + ",'" + resultJSON.ToJsonString() + "','" + time + "')";
                    SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);

                    //更新最新的数据
                    sql1 = @"SELECT count(*) FROM real_datas where station_id='" + resultJSON.equi + "' and data_id=" + 1;
                    int count = int.Parse(SqlHelper.ExecuteScalar(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1).ToString());
                    if (count == 0)
                    {
                        sql1 = "INSERT INTO real_datas(station_id,data_id,value,created_time) values('" + resultJSON.equi + "'," + 1 + ",'" + resultJSON.ToJsonString() + "','" + time + "')";
                        SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                    }
                    else
                    {
                        sql1 = "SELECT id,station_id,data_id,value from real_datas where station_id='" + resultJSON.equi + "' and data_id=" + 1;
                        DataSet ds = SqlHelper.GetDataSet(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                        int id = int.Parse(ds.Tables[0].Rows[0]["id"].ToString());

                        sql1 = "UPDATE real_datas set value = '" + resultJSON.ToJsonString() + "',created_time = '" + time + "' where id= " + id;
                        SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                    }

                    //如果有报警，加入报警日志
                    for (int i = 0; i < resultJSON.sensor.Count; i++)
                    {
                        if (resultJSON.sensor[i].type == 1) //CH1:主电源  CH2:控制柜电源
                        {
                            ValueData_DataItemType1 sensor1 = (ValueData_DataItemType1)resultJSON.sensor[i];
                            if (sensor1.CH1 == 0)
                            {
                                sql1 = String.Format("INSERT INTO alarm_histories (created_time,equi,sensorId,[type],[key],[desc]) VALUES('{0}'," +
                                    " N'{1}', {2}, {3}, N'{4}',N'{5}')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),resultJSON.equi,sensor1.id,sensor1.type,"CH1", "主电源停电");
                                SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                            }
                            if (sensor1.CH2 == 0)
                            {
                                sql1 = String.Format("INSERT INTO alarm_histories (created_time,equi,sensorId,[type],[key],[desc]) VALUES('{0}'," +
                                    " N'{1}', {2}, {3}, N'{4}',N'{5}')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), resultJSON.equi, sensor1.id, sensor1.type, "CH2", "控制柜电源停电");
                                SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                            }
                        }
                        else if (resultJSON.sensor[i].type == 2) // 火灾报警
                        {
                            ValueData_DataItemType2 sensor2 = (ValueData_DataItemType2)resultJSON.sensor[i];
                            if(sensor2.status == 1)
                            { 
                                sql1 = String.Format("INSERT INTO alarm_histories (created_time,equi,sensorId,[type],[key],[desc]) VALUES('{0}'," +
                                    " N'{1}', {2}, {3}, N'{4}',N'{5}')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), resultJSON.equi, sensor2.id, sensor2.type, "FireAlarm", "火灾报警");
                                SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                            }
                        }
                        else if (resultJSON.sensor[i].type == 3) //[0]:预留1，[1]：预留2，[2]：门禁，[3]:跑水
                        {
                            ValueData_DataItemType3 sensor3 = (ValueData_DataItemType3)resultJSON.sensor[i];
                            if (sensor3.status[3].Equals('1'))//跑水
                            {
                                sql1 = String.Format("INSERT INTO alarm_histories (created_time,equi,sensorId,[type],[key],[desc]) VALUES('{0}'," +
                                    " N'{1}', {2}, {3}, N'{4}',N'{5}')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), resultJSON.equi, sensor3.id, sensor3.type, "WaterOut", "跑水报警");
                                SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                            }

                            if (sensor3.status[2].Equals('1'))//门禁
                            {
                                sql1 = String.Format("INSERT INTO alarm_histories (created_time,equi,sensorId,[type],[key],[desc]) VALUES('{0}'," +
                                    " N'{1}', {2}, {3}, N'{4}',N'{5}')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), resultJSON.equi, sensor3.id, sensor3.type, "EntranceGuard", "门禁报警");
                                SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                            }

                            if (sensor3.status[1].Equals('1'))//预留2
                            {
                                sql1 = String.Format("INSERT INTO alarm_histories (created_time,equi,sensorId,[type],[key],[desc]) VALUES('{0}'," +
                                    " N'{1}', {2}, {3}, N'{4}',N'{5}')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), resultJSON.equi, sensor3.id, sensor3.type, "Reserve2", "预留2报警");
                                SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                            }

                            if (sensor3.status[0].Equals('1'))//预留1
                            {
                                sql1 = String.Format("INSERT INTO alarm_histories (created_time,equi,sensorId,[type],[key],[desc]) VALUES('{0}'," +
                                    " N'{1}', {2}, {3}, N'{4}',N'{5}')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), resultJSON.equi, sensor3.id, sensor3.type, "Reserve1", "预留1报警");
                                SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    showLogs(ex.Message);
                }
            }
            else if (strSRecMsg.IndexOf("equi") >=0 && strSRecMsg.IndexOf("imsi") >= 0 && strSRecMsg.IndexOf("temperature") >= 0)
            {
                try
                {
                    TemperatureInDoor resultJSON = JsonConvert.DeserializeObject<TemperatureInDoor>(strSRecMsg, new DataConverter());

                    showLogs("收到室内则温数据  equi=" + resultJSON.equi + ",imsi=" + resultJSON.imsi + ", modify-status=" + resultJSON.modifyStatus + ",upload-interval=" + resultJSON.uploadInterval + ",temperature=" + resultJSON.temperature.ToString());

                    String time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                    String sql1 = "INSERT INTO receive_history_new(station_id,data_id,value,created_time) values('" + resultJSON.imsi + "'," + 1 + ",'" + resultJSON.ToJsonString() + "','" + time + "')";
                    SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);

                    //更新最新的数据
                    sql1 = @"SELECT count(*) FROM real_datas where station_id='" + resultJSON.imsi + "' and data_id=" + 1;
                    int count = int.Parse(SqlHelper.ExecuteScalar(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1).ToString());
                    if (count == 0)
                    {
                        sql1 = "INSERT INTO real_datas(station_id,data_id,value,created_time) values('" + resultJSON.imsi + "'," + 1 + ",'" + resultJSON.ToJsonString() + "','" + time + "')";
                        SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                    }
                    else
                    {
                        sql1 = "SELECT id,station_id,data_id,value from real_datas where station_id='" + resultJSON.imsi + "' and data_id=" + 1;
                        DataSet ds = SqlHelper.GetDataSet(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                        int id = int.Parse(ds.Tables[0].Rows[0]["id"].ToString());

                        sql1 = "UPDATE real_datas set value = '" + resultJSON.ToJsonString() + "',created_time = '" + time + "' where id= " + id;
                        SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);
                    }

                    //发送到其他平台
                    try
                    {
                        SendToOtherPlatformData data = new SendToOtherPlatformData();
                        data.imsi = resultJSON.imsi;
                        data.equi = resultJSON.equi;
                        data.temperature = resultJSON.temperature;

                        String jsonStr = JsonConvert.SerializeObject(data);
                        restClient.Post(jsonStr, "cwmb/");

                        Console.WriteLine("发送成功");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                catch (Exception ex)
                {
                    showLogs(ex.Message);
                }
            }
            else
            {
                //showLogs("未处理数据=" + strSRecMsg);
            }

        }

        ///      
        /// 获取当前系统时间的方法    
        /// 当前时间     
        static DateTime GetCurrentTime()
        {
            DateTime currentTime = new DateTime();
            currentTime = DateTime.Now;
            return currentTime;
        }


        private void button3_Click(object sender, EventArgs e)
        {
            if (btStart.Text.Equals("停止"))
            {
                btStart.PerformClick();
                Application.Exit();
            }
            else
            {
                Application.Exit();
            }
        }

        private void btClear_Click(object sender, EventArgs e)
        {
            txtLog.Text = "";
        }

        private static void showError(Exception ex)
        {
            Form1.getInstance().txtError.Text += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + ex.StackTrace;
        }
        private void button2_Click_1(object sender, EventArgs e)
        {
            txtError.Text = "";
        }

        private void tmrForStart_Tick(object sender, EventArgs e)
        {
            btStart.PerformClick();
            tmrForStart.Enabled = false;
        }

        private void btClearHistoryData_Click(object sender, EventArgs e)
        {
            moveOldDataToHistory();
        }


        private void btClearErrorLogs_Click(object sender, EventArgs e)
        {
            txtError.Text = "";
        }

        private void moveOldDataToHistory()
        {
            if (DateTime.Now.Subtract(lastCheckMoveHistoryData).TotalHours > 10)
            {
                lastCheckMoveHistoryData = DateTime.Now;

                //检查数据记录个数
                String sql1 = "select count(*) from receive_history";
                int recordCount = (int)SqlHelper.ExecuteScalar(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);

                if (recordCount > 10000)
                {
                    sql1 = "select top 1 id from receive_history order by id desc"; //取得最后一条数据
                    DataSet ds = SqlHelper.GetDataSet(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);

                    long last_id = long.Parse(ds.Tables[0].Rows[0]["id"].ToString());
                    long id_to_move = last_id - 1000;

                    sql1 = "select count(*) from receive_history_olddata";
                    int old_count = (int)SqlHelper.ExecuteScalar(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);


                    sql1 = "insert into receive_history_olddata(station,data_id,link,time,ch1,ch2,ch3,ch4,ch5) select station,data_id,link,time,ch1,ch2,ch3,ch4,ch5 from receive_history where id <= " + id_to_move;
                    SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);

                    sql1 = "select count(*) from receive_history_olddata";
                    int new_count = (int)SqlHelper.ExecuteScalar(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);

                    if (new_count - old_count > 1000)
                    {
                        sql1 = "delete from receive_history where id <= " + id_to_move;
                        SqlHelper.ExecuteNonQuery(ConfigurationManager.AppSettings["ConnectString"], CommandType.Text, sql1, null);

                        showLogs("历史数据转换完成");
                    }
                }
            }
        }

        private void tmrCheckMoveHistory_Tick(object sender, EventArgs e)
        {
            if (chkAutoRemoveToHistory.Checked)
                moveOldDataToHistory();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //InputPassword dialog = new InputPassword();
            //DialogResult result = dialog.ShowDialog();

            //if (result == DialogResult.OK)
            //{
            //}
            //else {
            //    e.Cancel = true;
            //}


            if (btReadModbus.Text.Equals("停止读取Modbus"))
            {
                btReadModbus_Click(this, EventArgs.Empty);
            }

        }

        private void btReadModbus_Click(object sender, EventArgs e)
        {
            //查看文章  https://www.cnblogs.com/dathlin/p/13416030.html
            client = new MqttClient(new MqttConnectionOptions()
            {
                IpAddress = "127.0.0.1",
                Port = 1883,
            });
            // 接收到数据的时候进行触发
            client.OnMqttMessageReceived += Client_OnMqttMessageReceived; ;
            // 订阅服务器的主题，在连接成功后就去订阅
            client.OnClientConnected += m =>
            {
                m.SubscribeMessage("A");
            };
            client.ConnectServer();
        }

        private void Client_OnMqttMessageReceived(MqttClient client, string topic, byte[] payload)
        {
            // 切回主线程进行显示文本
            Invoke(new Action(() =>
            {
                Console.WriteLine(Encoding.UTF8.GetString(payload));
            }));
        }

        private void button1_Click_2(object sender, EventArgs e)
        {
            serverThread = new Thread(new ThreadStart(mqttServer));
            serverThread.Start();
        }

        private void mqttServer()
        {
            MqttServer server = new MqttServer();
            server.ServerStart(1883);
            int i = 0;
            while (true)
            {
                System.Threading.Thread.Sleep(1000);
                server.PublishTopicPayload("A", Encoding.UTF8.GetBytes(i.ToString()));
                i++;
            }
        }

        private void readModbus()
        {

            //var modbusRtu = new ModbusRtu(1);
            //modbusRtu.SerialPortInni("COM4", 9600, 8, System.IO.Ports.StopBits.One, System.IO.Ports.Parity.None);
            //modbusRtu.Open();

            var modbusRtu = new ModbusTcpNet("101.201.68.169", 6070, 1);
            OperateResult operateResult = modbusRtu.ConnectServer();


            //if (modbusRtu.IsOpen() == false)
            //{
            //    showLogs("打开设备失败");
            //    return;
            //}

            if (operateResult.IsSuccess == false)
            {
                showLogs("打开设备失败");
                return;
            }



            try
            {
                readData(modbusRtu, "s=0;x=3;0000", 9);
                readData(modbusRtu, "s=0;x=4;0000", 5);
                showLogs("");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                //if (modbusRtu.IsOpen() == true)
                //{
                //    modbusRtu.Close();

                //    if (modbusRtu.IsOpen() == true)
                //    {
                //        showLogs("关闭设备失败");
                //    }
                //}

                if (operateResult.IsSuccess)
                {
                    modbusRtu.ConnectClose();
                }
            }
        }

        private void readData(ModbusTcpNet modbusRtu, String address, ushort length)
        {
            OperateResult<Int16[]> datas = modbusRtu.ReadInt16(address, length);
            if (datas.IsSuccess)
            {
                String results = "";

                for (int i = 0; i < datas.Content.Length; i++)
                {
                    results += datas.Content[i].ToString() + ",";
                }

                showLogs("读取成功，" + results);
            }
            else
            {
                showLogs("读取失败：" + datas.ErrorCode);
            }
        }
        private void tmrReadModbus_Tick(object sender, EventArgs e)
        {
            readModbus();
        }

        private void btReadModbus_Click_1(object sender, EventArgs e)
        {
            if (btReadModbus.Text.Equals("读取Modbus"))
            {
                tmrReadModbus.Enabled = true;
                tmrReadModbus.Start();
                btReadModbus.Text = "停止读取Modbus";
            }
            else
            {
                tmrReadModbus.Enabled = false;
                tmrReadModbus.Stop();
                btReadModbus.Text = "读取Modbus";
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            var modbusRtu = new ModbusRtu(0);
            modbusRtu.SerialPortInni("COM4", 9600, 8, System.IO.Ports.StopBits.One, System.IO.Ports.Parity.None);
            modbusRtu.Open();

            if (modbusRtu.IsOpen() == false)
            {
                showLogs("打开设备失败");
                return;
            }

            try
            {
                writeData(modbusRtu, "s=0;x=3;0000", 1500);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (modbusRtu.IsOpen() == true)
                {
                    modbusRtu.Close();

                    if (modbusRtu.IsOpen() == true)
                    {
                        showLogs("关闭设备失败");
                    }
                }
            }
        }

        private void writeData(ModbusRtu modbusRtu, String address, Int16 newValue)
        {
            OperateResult or = modbusRtu.Write(address, newValue);
            if (or.IsSuccess)
            {
                showLogs("修改完成");
            }
            else
            {
                showLogs("修改失败");
            }
        }

        private void btReadValues_Click(object sender, EventArgs e)
        {
            if (txtCommand.Text.Trim().Equals(""))
            {
                MessageBox.Show(this, "请输入要发送的命令。");
                return;
            }


            String commandText = txtCommand.Text.Trim().Replace(" ", "");

            if (chkAutoAppendCRC16.Checked)
            {
                String commandTextNew = "";
                char[] charFruit = commandText.ToCharArray();
                for (int i = 0; i < charFruit.Length; i++)
                {
                    if (i > 0 && i % 2 == 0)
                    {
                        commandTextNew += " " + charFruit[i];
                    }
                    else
                    {
                        commandTextNew += charFruit[i];
                    }
                }
                commandText = commandTextNew;
                byte[] buffers = CRC.CRC16(commandText);
                for (int i = 0; i < buffers.Length; i++)
                {
                    String appendChar = String.Format("{0:X2}", buffers[i]).ToUpper();

                    commandText += " " + appendChar;
                }
            }



            showLogs("加入命令：" + commandText);
            commandToSend.Add(commandText.Replace(" ", ""));
        }

        private void btChange_Click(object sender, EventArgs e)
        {
            Double singleValue = bytesToDouble(txtData.Text.Trim());
            showLogs(txtData.Text.Trim() + "=" + singleValue.ToString());
        }

        private void btOperate_Click(object sender, EventArgs e)
        {
            String str = File.ReadAllText("d:\\jsondata.json", Encoding.UTF8);
            operateString("", str, 0);
        }

        private Double bytesToDouble(String valueByteStr)
        {
            String oriValue = valueByteStr;
            valueByteStr = valueByteStr.Replace(" ", "");
            byte[] datas = new byte[valueByteStr.Length / 2];
            for (int i = 0; i < valueByteStr.Length / 2; i++)
            {
                datas[3 - i] = Convert.ToByte(valueByteStr.Substring(i * 2, 2), 16);
            }
            Single singleValue = BitConverter.ToSingle(datas, 0);

            return singleValue;
        }

        private static bool isModbusData(String receiveData)
        {

            if (receiveData.Substring(0, 6) == "01 03 ")
            {
                return true;
            }

            return false;
        }

        private void parseModBusData(String receiveData)
        {
            ModbusData mobusData = new ModbusData();
            mobusData.ParseData(receiveData);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            /*if(chkAutoAppendCRC16.Checked)
            {
                byte[] results = HuanReZhanDataReceiver.CRC.CRC16(txtCommand.Text);

                for (int i = 0; i < results.Length; i++)
                {
                    Console.Write(results[i].ToString("X") + ",");
                }
                
            }*/

            btOperate_Click(sender, e);
            //增加一个测试注释。


        }

        private void tmrForSendModbusCommand_Tick(object sender, EventArgs e)
        {
            if (canSend == false) return;

            //showLogs("发送命令");
            //btReadValues_Click(btReadValues, EventArgs.Empty);
        }

        private void txtCommand_TextChanged(object sender, EventArgs e)
        {

        }

        private void btMQTT_Click(object sender, EventArgs e)
        {
            if (btMQTT.Text.Equals("启动MQTT"))
            {
                btMQTT.Text = "停止MQTT";

                clientService = new MqttClientService();
                clientService.MqttClientStart();
            }
            else
            {
                if(clientService != null)
                {
                    clientService.MqttClientStop();
                }

                btMQTT.Text = "启动MQTT";
            }
        }

        private void button2_Click_2(object sender, EventArgs e)
        {

            try
            {
                SendToOtherPlatformData data = new SendToOtherPlatformData();
                data.imsi = "460087330003460";
                data.equi = "2307000027";
                data.temperature = 20.0D;

                String jsonStr = JsonConvert.SerializeObject(data);
                restClient.Post(jsonStr, "cwmb/");

                Console.WriteLine("发送成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }

    public class ModbusData
    {
        public String name { get; set; }

        public String belongto { get; set; }
        public byte Address { get; set; } //地址

        public byte FunctionNo { get; set; } //功能号

        public byte PackageLength { get; set; } //包长度

        public float OutdoorTemp { get; set; } //户外温度

        public float YiCiGongShuiTemp { get; set; } // 一次供水温度

        public float YiCiHuiShuiTemp { get; set; } //一次回水温度

        public float ErCiGongShuiTemp { get; set; } // 二次供水温度

        public float ErCiHuiShuiTemp { get; set; } //二次回水温度

        public float ShuiXiangYeWei { get; set; } //水箱液位
        public float YiCiTiaoJieFaFaWei { get; set; } //一次调节阀阀位
        public float YiCiShunShiLiuLiang { get; set; } //一次瞬时流量
        public float YiCiGongShuiYaLi { get; set; } //一次供水压力

        public float YiCiHuiShuiYaLi { get; set; }//一次回水压力

        public float ErCiGongShuiYaLi { get; set; } //二次供水压力

        public float ErCiHuiShuiYaLi { get; set; }//二次回水压力

        public float YiHaoXunHuanBengPinLv { get; set; } //一号循环泵频率

        public float YiHaoXunHuanBengYunXinTingZhi { get; set; } //一号循环泵运行停止

        public float YiHaoXunHuanBengGuZhang { get; set; } //一号循环泵故障
        public float ErHaoXunHuanBengYunXinTingZhi { get; set; } //二号循环泵运行停止

        public float ErHaoXunHuanBengGuZhang { get; set; } //二号循环泵故障

        public float YiHaoXunHuanBengBenDiYuanCheng { get; set; } //一号循环泵本地远程
        public float ErHaoXunHuanBengBenDiYuanCheng { get; set; } //二号循环泵本地远程

        public float YiHaoXunHuanBengBianPinZhuangTai { get; set; } //一号补水泵变频状态
        public float YiHaoXunHuanBengDianLiu { get; set; } //一号循环泵电流
        public float ERHaoXunHuanBengPinLv { get; set; } //二号循环泵频率
        public float ERHaoXunHuanBengDianLiu { get; set; } //二号循环泵电流

        public float BuShuiBengPinLv { get; set; } //补水泵频率
        public float BuShuiBengDianLiu { get; set; } //补水泵电流

        public float YiCiTiaoJieFaKongZhiShuChu { get; set; } //一次调节阀控制输出
        public float YiCiCeTiaoJieFaPIDShouZiDong { get; set; } //一次侧调节阀PID手自动
        public float YiHaoMuGuanYaLi { get; set; } //一号母管压力
        public float ErHaoMuGuanYaLi { get; set; } //二号母管压力
        public float YiHaoMuGuanWenDu { get; set; } //一号母管温度
        public float ErHaoMuGuanWenDu { get; set; } //二号母管温度
        public float ErCiShunShiLiuLiang { get; set; } //二次瞬时流量

        public float ErHaoBuShuiBengBianPinZhuangTai { get; set; } //二号补水泵变频状态
        public float BuShuiBengBianPinGuZhangXinHao { get; set; } //补水泵变频故障信号
        public float YiHaoBuShuiBengGongPinZhuangTai { get; set; } //一号补水泵工频状态
        public float ErHaoBuShuiBengGongPinZhuangTai { get; set; } //二号补水泵工频状态
        public float XunHuanBengPIDHuiLuYaChaSheDingZhi { get; set; }//循环泵PID回路压差设定值
        public float BuShuiBengPIDHuiLuErCiHuiShuiYaLiSheDingZhi { get; set; }//补水泵PID回路二次回水压力设定值

        public float BuShuiBengDiXianSheDing { get; set; }//补水泵底线设定
        public float BuShuiBengGaoXianSheDing { get; set; }//补水泵高限设定
        public float XunHuanBengDiXianSheDing { get; set; }//循环泵底限设定

        public float YiHaoBuShuiBengGongPinGuZhangZhuangTai { get; set; }//一号补水泵工频故障状态
        public float ErHaoBuShuiBengGongPinGuZhangZhuangTai { get; set; }//二号补水泵工频故障状态
        public float YiHaoBuShuiBengShouZiDongZhuangTai { get; set; }//一号补水泵手自动状态
        public float ErHaoBuShuiBengShouZiDongZhuangTai { get; set; }//二号补水泵手自动状态

        public void ParseData(String data)
        {
            String[] parts = data.Split(' ');
            byte[] bytesData = new byte[parts.Length];

            for (int i = 0; i < bytesData.Length; i++)
            {
                bytesData[i] = byte.Parse(parts[i], System.Globalization.NumberStyles.AllowHexSpecifier);
            }

            int pos = 0;

            Address = bytesData[pos]; pos++;
            FunctionNo = bytesData[pos]; pos++;
            PackageLength = bytesData[pos]; pos++;

            OutdoorTemp = ParseFloat(bytesData, pos, 4); pos += 4;
            YiCiGongShuiTemp = ParseFloat(bytesData, pos, 4); pos += 4;
            YiCiHuiShuiTemp = ParseFloat(bytesData, pos, 4); pos += 4;
            ErCiGongShuiTemp = ParseFloat(bytesData, pos, 4); pos += 4;
            ErCiHuiShuiTemp = ParseFloat(bytesData, pos, 4); pos += 4;
            ShuiXiangYeWei = ParseFloat(bytesData, pos, 4); pos += 4;
            YiCiTiaoJieFaFaWei = ParseFloat(bytesData, pos, 4); pos += 4;
            YiCiShunShiLiuLiang = ParseFloat(bytesData, pos, 4); pos += 4;
            YiCiGongShuiYaLi = ParseFloat(bytesData, pos, 4); pos += 4;
            YiCiHuiShuiYaLi = ParseFloat(bytesData, pos, 4); pos += 4;
            ErCiGongShuiYaLi = ParseFloat(bytesData, pos, 4); pos += 4;
            ErCiHuiShuiYaLi = ParseFloat(bytesData, pos, 4); pos += 4;
            YiHaoXunHuanBengPinLv = ParseFloat(bytesData, pos, 4); pos += 4;
            YiHaoXunHuanBengYunXinTingZhi = ParseFloat(bytesData, pos, 4); pos += 4;
            YiHaoXunHuanBengGuZhang = ParseFloat(bytesData, pos, 4); pos += 4;
            ErHaoXunHuanBengYunXinTingZhi = ParseFloat(bytesData, pos, 4); pos += 4;
            ErHaoXunHuanBengGuZhang = ParseFloat(bytesData, pos, 4); pos += 4;
            YiHaoXunHuanBengBenDiYuanCheng = ParseFloat(bytesData, pos, 4); pos += 4;
            ErHaoXunHuanBengBenDiYuanCheng = ParseFloat(bytesData, pos, 4); pos += 4;
            pos += 4;
            YiHaoXunHuanBengBianPinZhuangTai = ParseFloat(bytesData, pos, 4); pos += 4;
            YiHaoXunHuanBengDianLiu = ParseFloat(bytesData, pos, 4); pos += 4;
            ERHaoXunHuanBengPinLv = ParseFloat(bytesData, pos, 4); pos += 4;
            ERHaoXunHuanBengDianLiu = ParseFloat(bytesData, pos, 4); pos += 4;
            pos += 4;
            pos += 4;
            BuShuiBengPinLv = ParseFloat(bytesData, pos, 4); pos += 4;
            BuShuiBengDianLiu = ParseFloat(bytesData, pos, 4); pos += 4;
            pos += 4;
            pos += 4;
            pos += 4;
            YiCiTiaoJieFaKongZhiShuChu = ParseFloat(bytesData, pos, 4); pos += 4;
            YiCiCeTiaoJieFaPIDShouZiDong = ParseFloat(bytesData, pos, 4); pos += 4;
            pos += 4;
            pos += 4;
            pos += 4;
            pos += 4;
            YiHaoMuGuanYaLi = ParseFloat(bytesData, pos, 4); pos += 4;
            ErHaoMuGuanYaLi = ParseFloat(bytesData, pos, 4); pos += 4;
            YiHaoMuGuanWenDu = ParseFloat(bytesData, pos, 4); pos += 4;
            ErHaoMuGuanWenDu = ParseFloat(bytesData, pos, 4); pos += 4;
            ErCiShunShiLiuLiang = ParseFloat(bytesData, pos, 4); pos += 4;
            pos += 4;
            pos += 4;
            pos += 4;
            pos += 4;
            ErHaoBuShuiBengBianPinZhuangTai = ParseFloat(bytesData, pos, 4); pos += 4;
            BuShuiBengBianPinGuZhangXinHao = ParseFloat(bytesData, pos, 4); pos += 4;
            YiHaoBuShuiBengGongPinZhuangTai = ParseFloat(bytesData, pos, 4); pos += 4;
            ErHaoBuShuiBengGongPinZhuangTai = ParseFloat(bytesData, pos, 4); pos += 4;

            for (int i = 0; i < 34; i++)
            {
                pos += 4;
            }
            if (pos > bytesData.Length) return;

            XunHuanBengPIDHuiLuYaChaSheDingZhi = ParseFloat(bytesData, pos, 4); pos += 4;
            for (int i = 0; i < 20; i++)
            {
                pos += 4;
            }
            if (pos > bytesData.Length) return;

            BuShuiBengPIDHuiLuErCiHuiShuiYaLiSheDingZhi = ParseFloat(bytesData, pos, 4); pos += 4;
            for (int i = 0; i < 3; i++)
            {
                pos += 4;
            }
            if (pos > bytesData.Length) return;

            BuShuiBengDiXianSheDing = ParseFloat(bytesData, pos, 4); pos += 4;
            if (pos > bytesData.Length) return;

            BuShuiBengGaoXianSheDing = ParseFloat(bytesData, pos, 4); pos += 4;
            if (pos > bytesData.Length) return;

            XunHuanBengDiXianSheDing = ParseFloat(bytesData, pos, 4); pos += 4;
            if (pos > bytesData.Length) return;

            for (int i = 0; i < 26; i++)
            {
                pos += 4;
            }
            if (pos > bytesData.Length) return;

            YiHaoBuShuiBengGongPinGuZhangZhuangTai = ParseFloat(bytesData, pos, 4); pos += 4;
            if (pos > bytesData.Length) return;

            ErHaoBuShuiBengGongPinGuZhangZhuangTai = ParseFloat(bytesData, pos, 4); pos += 4;
            if (pos > bytesData.Length) return;

            YiHaoBuShuiBengShouZiDongZhuangTai = ParseFloat(bytesData, pos, 4); pos += 4;
            if (pos > bytesData.Length) return;

            ErHaoBuShuiBengShouZiDongZhuangTai = ParseFloat(bytesData, pos, 4); pos += 4;
            if (pos > bytesData.Length) return;


            Console.WriteLine(this.ToString());
        }
        public Single ParseFloat(byte[] parts, int pos, int length)
        {
            byte[] datas = new byte[4];
            for (int i = 0; i < length; i++)
            {
                datas[3 - i] = parts[pos + i];
            }
            Single singleValue = BitConverter.ToSingle(datas, 0);
            //singleValue = Single.Parse(singleValue.ToString("#0.00"));
            return singleValue;
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            Type type = this.GetType();

            foreach (PropertyInfo p in type.GetProperties())
            {
                sb.AppendLine(p.Name + "=" + p.GetValue(this, null).ToString());
            }

            return sb.ToString();
        }
    }

    public class DataConverter : DataCreationConverter<ValueData_DataItemBase>
    {
        protected override ValueData_DataItemBase Create(Type objectType, JObject jObject)
        {
            if (FieldExists("type", jObject, out Int64 typeValue))
            {
                if (typeValue == 1)
                {
                    return new ValueData_DataItemType1();
                }
                else if (typeValue == 2)
                {
                    return new ValueData_DataItemType2();
                }
                else if (typeValue == 3)
                {
                    return new ValueData_DataItemType3();
                }
                else
                {
                    throw new Exception("未找到对应的子类");
                }
            }
            else
            {
                throw new Exception("未找到对应的子类");
            }
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        private bool FieldExists(String fieldName, JObject jObject, out Int64 entityName)
        {
            entityName = jObject[fieldName] == null ? 0 : Int64.Parse(jObject[fieldName].ToString());
            return jObject[fieldName] != null;
        }
    }


    public abstract class DataCreationConverter<T> : JsonConverter
    {
        protected abstract T Create(Type objectType, JObject jObject);
        public override bool CanConvert(Type objectType)
        {
            return typeof(T).IsAssignableFrom(objectType);
        }


        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jobject = JObject.Load(reader);
            T target = Create(objectType, jobject);
            serializer.Populate(jobject.CreateReader(), target);

            return target;
        }
    }


    public class ValueData
    {
        public String name { get; set; }
        public String belongto { get; set; }
        public Int32 CH1 { get; set; }
        public Int32 CH2 { get; set; }
        public Int32 CH3 { get; set; }
        public Int32 CH4 { get; set; }
        public Int32 CH5 { get; set; }


    }

    public class ValueData2
    {
        public String equi { get; set; }
        public Int32 modifyStatus { get; set; }
        public Int32 uploadInterval { get; set; }
        public List<ValueData_DataItemBase> sensor { get; set; }
    }

    public class ValueData_DataItemBase
    {
        public Int64 id { get; set; }
        public Int64 linked { get; set; }
        public Int64 type { get; set; }
    }

    public class ValueData_DataItemType1 : ValueData_DataItemBase
    {
        public Double CH1 { get; set; }
        public Double CH2 { get; set; }

        public override string ToString()
        {
            Dictionary<String, Object> val = new Dictionary<string, object>();
            val.Add("linked", linked);
            val.Add("type", type);
            val.Add("CH1", CH1);
            val.Add("CH2", CH2);

            return JsonConvert.SerializeObject(val);
        }
    }

    public class ValueData_DataItemType2 : ValueData_DataItemBase
    {
        public Int64 status { get; set; }

        public override string ToString()
        {
            Dictionary<String, Object> val = new Dictionary<string, object>();
            val.Add("linked", linked);
            val.Add("type", type);
            val.Add("status", status);

            return JsonConvert.SerializeObject(val);
        }
    }

    public class ValueData_DataItemType3 : ValueData_DataItemBase
    {
        public String status { get; set; }

        public override string ToString()
        {
            Dictionary<String, Object> val = new Dictionary<string, object>();
            val.Add("linked", linked);
            val.Add("type", type);
            val.Add("status", status);

            return JsonConvert.SerializeObject(val);
        }
    }

    
    //{
    //    "equi": "1234567890", /* 室内测温模块出厂编号*/
    //    "imsi": "460113004670402", /* SIM卡识别号*/
    //    "modify-status": 0, /* 0=正常上传数据返回，1=修改参数返回 */
    //    "upload-interval": 0, /* 采集终端上传数据的间隔时间(0-65535 秒)，为0时=不上传 */
    //    "temperature": 20.0 /* 当前环境的采样温度，单位：℃ */
    //}
    //{"equi":"2308010000","imsi":"460084682100681","modify-status":0,"upload-interval":3600,"temperature":29.33872
    public class TemperatureInDoor
    {
        public String equi { get; set; }
        public String imsi { get; set; }
        public Int32 modifyStatus { get; set; }
        public Int32 uploadInterval { get; set; }
        public Double temperature { get; set; }
    }

    public class SendToOtherPlatformData {
        public String equi { get; set; }
        public String imsi { get; set; }
        public Double temperature { get; set; }
    }
}

